/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  EscapeActivity.java   
 * @Package com.jiyi.activity.escape   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-23 下午4:09:41   
 * @version V1.0     
 */
package com.jiyi.activity.escape;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.jiyi.bean.owner.PlanBean;
import com.jiyi.bean.owner.PlanBean.PlanEquip;
import com.jiyi.bean.owner.PositionPoint;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.PhotoClickInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.CanTouchImageView;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DeviceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: EscapeActivity
 * @Description:TODO(逃生定位)
 * @author: HYM
 * @date: 2017-9-23 下午4:09:41
 * 
 */
public class EscapeActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.ivPic)
	CanTouchImageView ivPic;

	@BindView(R.id.llDisplay)
	LinearLayout llDisplay;

	@BindView(R.id.tvBuildNo)
	TextView tvBuildNo;
	@BindView(R.id.tvLayoutName)
	TextView tvLayoutName;
	@BindView(R.id.tvDescribe)
	TextView tvDescribe;
	
	@BindView(R.id.rlPoint)
	RelativeLayout rlPoint;
	@BindView(R.id.llPoint)
	LinearLayout llPoint;
	@BindView(R.id.tvPoint)
	TextView tvPoint;
	@BindView(R.id.llCanclePoint)
	LinearLayout llCanclePoint;
	@BindView(R.id.tvCancelPoint)
	TextView tvCancelPoint;

	String floorId;
	// 平面图对象
	PlanBean planBean;
	// 当前设备对象
	PlanEquip planEquip;

	// 进度条
	Dialog dialog;
	
	float xPoint=0,yPoint=0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_escape);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getIntentData();
		setTop();
		setAddEquipViewStatus();
		getData();
		resetPoint();
	}
	
	private void setAddEquipViewStatus() {
		ivPic.setmPhotoClickInterface(new PhotoClickInterface() {

			@Override
			public void onPhotoClcik(float x, float y,float xRatio,float yRatio) {
				xPoint = x;
				yPoint = y;
			}

			@Override
			public void onPointClick(String equipment_id,float x, float y,float xRatio,float yRatio) {
				for (int i = 0; i < planBean.getEquipList().size(); i++) {
					PlanEquip tempEquip = planBean.getEquipList().get(i);
					if (tempEquip.getId().equals(equipment_id)) {
						//计算用户点位的点与当前点击的点的直线距离
						float a,b,c;
						//取绝对值的长
						a = Math.abs(xPoint- x);
						//取绝对值的宽
						b = Math.abs(yPoint -y);
						//用勾股定理取直线的值
						c = (float) Math.sqrt(a*a+b*b);
						ToastUtil.getInstances().showMsg("目标位置距离您当前位置"+(c*planBean.getRatio()/100) +"米");
						break;
					}
				}
			}
		});
	}

	private void getIntentData() {
		floorId = getIntent().getStringExtra("floorId");
	}

	private void setTop() {
		tvTitle.setText("");
		tvSearch.setVisibility(View.GONE);
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("floor_id", floorId);
		params.put("type", "1");

		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_OWNER_FLOOR_INFO, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								planBean = new Gson().fromJson(data,
										PlanBean.class);
								tvTitle.setText(planBean.getBuilding()
										+ planBean.getFloor_no());
								tvBuildNo.setText(planBean.getBuilding());
								tvLayoutName.setText(planBean.getFloor_no());
								tvDescribe.setText(planBean.getDescribe());
								Glide.with(getContext())
										.load(planBean.getMap())
										.asBitmap()
										// 加入了计算高度的方法
										.listener(
												new RequestListener<String, Bitmap>() {
													@Override
													public boolean onException(
															Exception e,
															String model,
															Target<Bitmap> target,
															boolean isFirstResource) {
														return false;
													}

													@Override
													public boolean onResourceReady(
															Bitmap resource,
															String model,
															Target<Bitmap> target,
															boolean isFromMemoryCache,
															boolean isFirstResource) {
														if (ivPic == null) {
															return false;
														}
														ViewGroup.LayoutParams params = ivPic
																.getLayoutParams();
														int vw = ivPic
																.getWidth()
																- ivPic.getPaddingLeft()
																- ivPic.getPaddingRight();
														Drawable drawable = new BitmapDrawable(
																resource);
														float scale = (float) vw
																/ (float) drawable
																		.getIntrinsicWidth();
														int vh = Math.round(drawable
																.getIntrinsicHeight()
																* scale);
														params.height = vh
																+ ivPic.getPaddingTop()
																+ ivPic.getPaddingBottom();
														ivPic.setLayoutParams(params);
														return false;
													}
												})
										.into(new SimpleTarget<Bitmap>(
												DeviceUtil.getInstance()
														.getScreenWidth() / 2,
												DeviceUtil.getInstance()
														.getScreenHeight() / 2) {

											@Override
											public void onResourceReady(
													Bitmap bitmap,
													GlideAnimation glideAnimation) {
												ivPic.setImageBitmap(bitmap);
												ivPic.setBmp(bitmap);
												Bitmap waterBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon_location_on);
												ivPic.setWaterBitmap(waterBitmap);
												setMaps(planBean.getEquipList());
											}

											public void onLoadFailed(
													Exception e,
													Drawable errorDrawable) {
												ivPic.setImageBitmap(null);
												ivPic.setBmp(null);
											};
										});

							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	Context getContext() {
		return this;
	}

	void setMaps(final List<PlanEquip> goodsMaps) {
		final ArrayList<PositionPoint> positionPoints = new ArrayList<PositionPoint>();
		for (int i = 0; i < goodsMaps.size(); i++) {
			final int temp = i;
			PositionPoint point = new PositionPoint();
			point.setPointX(goodsMaps.get(temp).getX_axis());
			point.setPointY(goodsMaps.get(temp).getY_axis());
			point.setId(goodsMaps.get(temp).getId());
			positionPoints.add(point);

			Glide.with(this.getContext()).load(goodsMaps.get(i).getIcon())
					.asBitmap().into(new SimpleTarget<Bitmap>() {
						@Override
						public void onResourceReady(Bitmap bitmap,
								GlideAnimation glideAnimation) {
                            int color=R.color.half_half_half_transparency;

                            ivPic.loadWaterList(bitmap, goodsMaps.get(temp)
									.getX_axis(), goodsMaps.get(temp)
									.getY_axis(), false,color,255);
						}
					}); // 方法中设置asBitmap可以设置回调类型
		}
		ivPic.setPositionPoints(positionPoints,false);
	}

	@OnClick({ R.id.tvBack,R.id.tvPoint ,R.id.tvCancelPoint})
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvPoint:
			llCanclePoint.setVisibility(View.VISIBLE);
			llPoint.setVisibility(View.GONE);
			ivPic.setClick_status(1);
			break;
		case R.id.tvCancelPoint:
			if (xPoint == 0 && yPoint == 0) {
				ToastUtil.getInstances().showMsg("请先放置当前位置");
				return;
			}
			llCanclePoint.setVisibility(View.GONE);
			llPoint.setVisibility(View.VISIBLE);
			ivPic.setClick_status(2);
			break;
		default:
			break;
		}
	}
	
	void resetPoint() {
		llCanclePoint.setVisibility(View.GONE);
		rlPoint.setVisibility(View.VISIBLE);
		tvPoint.setVisibility(View.VISIBLE);
		ivPic.setClick_status(0);
	}
}
